package com.sun.test22.Test;

import com.sun.test22.mapper.UserMapper;
import com.sun.test22.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MyBatisTest {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            User newUser = new User();
            newUser.setUsername("testuser");
            newUser.setEmail("testuser@example.com");

            mapper.insertUser(newUser);
            session.commit();

            User user = mapper.getUserById(newUser.getId());
            System.out.println(user.getUsername() + ", " + user.getEmail());
        }
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            User userWithRole = mapper.getUserWithRoleById(1);
            if (userWithRole != null && userWithRole.getRole() != null) {
                System.out.println(userWithRole.getUsername() + ", " + userWithRole.getEmail() + ", " + userWithRole.getRole().getRoleName());
            } else {
                System.out.println("No user found with that ID.");
            }
        }
    }
}
